<template>
  <div class="hospital pad">
    <div class="head">
      <span>医院管理</span>
    </div>
    <el-tabs type="border-card">
      <el-tab-pane label="医院管理">
        <el-button type="primary" @click="openAddHospitalDialog" class="m-t-b">
          <i class="el-icon-plus"></i>
          添加医院
        </el-button>
        <el-table :data="hospitalList" stripe border class="m-t-b" v-loading="loading">
          <el-table-column label="医院名称" prop="enterpriseName"></el-table-column>
          <el-table-column label="医院简称" prop="forShort"></el-table-column>
          <el-table-column label="医院所属省" prop="province">
            <!-- <template slot-scope="scopes">
              <img
                v-if="scopes.row.hospitalUrl"
                style="width: 120px; height: 120px"
                :src="scopes.row.hospitalUrl"
              />
              <el-button
                type="info"
                v-if="!scopes.row.hospitalUrl"
                @click="handleGen(scopes.row)"
              >
                生成二维码
              </el-button>
            </template> -->
          </el-table-column>
          <el-table-column label="医院所属市" prop="city">
            <!-- <template slot-scope="scope">
              {{getAreaName(scope.row.)}}
            </template> -->

          </el-table-column>
          <el-table-column label="创建时间" prop="createDate"></el-table-column>
          <el-table-column label="操作" fixed="right" width="200">
            <!-- <template slot-scope="scope"> -->
              <!-- <el-button circle icon="el-icon-view" type="default" @click="goHospitalDetail(scope.row)"></el-button> -->
              <!-- <el-button circle icon="el-icon-edit" type="primary" @click="openEditHospitalDialog(scope.row)"></el-button> -->
              <!-- <el-button circle icon="el-icon-delete" type="danger" @click="deleteHospital(scope.row)"></el-button> -->
            <!-- </template> -->
          </el-table-column>
        </el-table>
        <el-pagination
          class="flex m-t-b"
          :page-size="pageSize"
          layout="prev, pager, next"
          @current-change="handlePagi"
          :total="total"
          :current-page="curPage"
        >
        </el-pagination>
      </el-tab-pane>
      <el-tab-pane label="科室管理">
        <el-button type="primary" class="m-t-b" @click="openAddDepDialog">
          <i class="el-icon-plus"></i>
          添加科室
        </el-button>
        <el-table :data="depList" border stripe class="m-t-b" v-loading="showDep">
          <el-table-column label="科室名称" prop="department"></el-table-column>
          <el-table-column label="创建时间" prop="createDate"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button circle icon="el-icon-edit" @click="openEditDepDialog(scope.row)"></el-button>
              <el-button type="danger" circle icon="el-icon-delete" @click="handleDelete(scope.row, 1)"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="flex m-t-b"
          :page-size="pageSize"
          layout="prev, pager, next"
          @current-change="handleDepPagi"
          :total="depTotal"
        >
        </el-pagination>
      </el-tab-pane>
      <el-tab-pane label="职称管理">
        <el-button type="primary" class="m-t-b" @click="openAddCareerDialog">
          <i class="el-icon-plus"></i>
          添加职称
        </el-button>
        <el-table :data="careerList" stripe border class="m-t-b" v-loading="showCareer">
          <el-table-column label="职称" prop="doctorTitle"></el-table-column>
          <el-table-column label="创建时间" prop="createDate"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button circle icon="el-icon-edit" @click="openEditCareerDialog(scope.row)"></el-button>
              <el-button circle icon="el-icon-delete" type="danger" @click="handleDelete(scope.row, 2)"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="flex m-t-b"
          :page-size="pageSize"
          layout="prev, pager, next"
          @current-change="handleCareerPagi"
          :total="careerTotal"
        >
        </el-pagination>
      </el-tab-pane>
    </el-tabs>
    <el-dialog :title="hospitalDialogTitle" :visible.sync="showHospitalDialog">
      <el-form :model="hospital" label-position="top" :rules="rules" ref="hospital">
        <el-form-item label="医院名称" prop="hospitalName">
          <el-input v-model="hospital.hospitalName" />
        </el-form-item>
        <el-form-item label="医院标识" prop="hospitalCode">
          <el-input v-model="hospital.hospitalCode" />
        </el-form-item>
        <el-form-item label="医院位置信息" prop="areaId">
          <el-select v-model="selectCountry" @change="provinceChange" placeholder="省">
            <el-option v-for="(item, i) in countries" :key="i" :value="item.id" :label="item.cname"></el-option>
          </el-select>
          <el-select v-model="hospital.areaId" placeholder="市">
            <el-option v-for="(item, i) in cities" :key="i" :value="item.id" :label="item.cname"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="hideHospitalDialog">取 消</el-button>
        <el-button type="primary" @click="fetchAddHospital('hospital')" :loading="isDoing">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="departmentDialogTitle" :visible.sync="showDepartmentDialog">
      <el-form :model="department" :rules="rules" ref="department" label-position="top">
        <el-form-item label="科室名称" prop="department">
          <el-input v-model="department.department" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="hideDepDialog">取 消</el-button>
        <el-button type="primary" @click="fetchAddDep('department')" :loading="isDoing">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="careerDialogTitle" :visible.sync="showCareerDialog">
      <el-form :model="career" ref="career" :rules="rules" label-position="top">
        <el-form-item label="职称" prop="doctorTitle">
          <el-input v-model="career.doctorTitle" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="hideCareerDialog">取 消</el-button>
        <el-button type="primary" @click="fetchAddCareer('career')" :loading="isCDoing">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  addHospital,
  updateHospital,
  deleteHospital,
  getHospitalByPage,
  addDepartment,
  updateDepartment,
  deleteDepartment,
  getDepartmentByPage,
  addCareerTitle,
  updateCareerTitle,
  deleteCareerTitle,
  getCareerTitleByPage,
  getAllAreaNoPage,
  getAllArea,
  genHospitalQRCode
} from '../api/hospitalAPI';
import { formatDate } from '../util'
export default {
  name: 'Hospital',
  data () {
    return {
      curPage: 1,
      isDoing: false,
      hospitalDialogTitle: '添加医院',
      showHospitalDialog: false,
      hospital: {
        // hospitalName: '',
        enterpriseName: '',
        hospitalCode: '',
        areaId: '',
        hospitalUrl: null
      },
      department: {
        department: ''
      },
      depTotal: 0,
      isCDoing: false,
      departmentDialogTitle: '添加科室',
      showDepartmentDialog: false,
      hospitalList: [],
      hospitalId: '',
      loading: false,
      total: 0,
      pageSize: 10,
      showDep: false,
      depList: [],

      career: {
        doctorTitle: ''
      },
      careerTotal: 0,
      careerList: [],
      showCareer: false,
      careerDialogTitle: '添加职称',
      showCareerDialog: false,
      countries: [],
      selectCountry: null,
      cities: [],
      allAreaList: [],



      rules: {
        hospitalName: [
          { required: true, message: '医院名称不能为空', trigger: 'blur' }
        ],
        hospitalCode: [
          { required: true, message: '医院标识不能为空', trigger: 'blur' }
        ],
        department: [
          { required: true, message: '科室名称不能为空', trigger: 'blur' }
        ],
        doctorTitle: [
          { required: true, message: '职称不能为空', trigger: 'blur' }
        ],
        areaId: [
          { required: true, message: '市不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    provinceChange (e) { // 省选择事件
      this.fetchAreaById(Number(e))
    },
    openAddHospitalDialog () { // 打开添加医院弹出框
      // this.hospital.hospitalName = '';
      // this.hospital.hospitalCode = '';
      // this.hospital.areaId = '';
      // this.selectCountry = '';
      // this.hospitalDialogTitle = '添加医院';
      // this.showHospitalDialog = true

      console.log(this.hospitalList);
      this.$router.push({
         path: '/organization/add?type=' + 3,
         query: {
           idccc: 1,
         }
      })
    },
    hideHospitalDialog () { // 隐藏医院弹出框
      this.showHospitalDialog = false
    },
    fetchAddHospital (name) { // 添加医院逻辑
      this.$refs[name].validate(valid => {
        if (valid) {
          this.isDoing = true;
          if (this.hospitalDialogTitle === '添加医院') {
            addHospital(this.hospital)
            .then(res => {
              if (res.data.code === 1) {
                this.$message({
                  type: 'success',
                  message: '添加成功!'
                });
                let { hospitalId, hospitalName } = res.data.data;
                this.fetchGenQRCode(hospitalId, hospitalName);
              } else {
                this.$message.error(res.data.msg || '服务异常')
              }
            })
            .catch(e => {
              this.isDoing = false;
              this.$message.error('服务异常!')
            })
          } else {
            updateHospital({
              hospitalId: this.hospitalId,
              ...this.hospital
            })
            .then(res => {
              if (res.data.code === 1) {
                this.$message({
                  type: 'success',
                  message: '修改成功!'
                });
                let { hospitalId, hospitalName } = res.data.data;
                this.fetchGenQRCode(hospitalId, hospitalName)
              } else {
                this.$message.error(res.data.msg || '服务异常!')
              }
            })
            .catch(e => {
              this.isDoing = false;
              this.$message.error('服务异常!')
            })
          }
        } else {
          return false
        }
      })
    },
    fetchHospitals (index) { // 分页查询医院
      this.loading = true;
      getHospitalByPage({
        count: this.pageSize,
        index,
        queryParam: {
          type: 3,
        }
      })
      .then(res => {
        console.log(res);
        if (res.data.code === 1) {
          let list = res.data.data.list || [];
          this.total = res.data.data.totalRecord;
          this.hospitalList = list.map(item => {
            item.createDate = formatDate(item.createDate, 'ZH');
            return item
          })
        } else {
          this.$message.error(res.data.msg || '服务异常!')
        };
        this.loading = false
      })
      .catch(e => {
        this.loading = false;
        this.$message.error('服务异常!')
      })
    },
    handlePagi (page) { // 分页事件
      this.curPage = page;
      this.fetchHospitals(page)
    },
    openEditHospitalDialog (data) { // 打开修改医院弹出框
      this.hospitalId = data.hospitalId;
      this.hospital.hospitalName = data.hospitalName;
      this.hospital.hospitalCode = data.hospitalCode;
      this.hospital.areaId = Number(data.areaId);
      this.selectCountry = data.parentId;
      this.fetchAreaById(data.parentId);
      this.hospitalDialogTitle = '修改医院';
      this.showHospitalDialog = true
    },
    deleteHospital (data) { // 删除医院
      this.$confirm(`确定将医院: ${data.hospitalName} 删除吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(res => {
        deleteHospital(data.hospitalId)
        .then(res => {
          if (res.data.code === 1) {
            this.$message({
              type: 'success',
              message: '删除成功'
            });
            this.fetchHospitals(1)
          } else {
            this.$message.error(res.data.msg || '服务异常!')
          }
        })
        .catch(e => {
          this.$message.error('服务异常!')
        })
      })
      .catch(e => {
        this.$message({
          type: 'info',
          message: '取消删除'
        })
      })
    },
    fetchDepartment (index) { // 分页查询部门
      this.showDep = true;
      getDepartmentByPage({
        count: this.pageSize,
        index
      })
      .then(res => {
        if (res.data.code === 1) {
          let list = res.data.data.list || [];
          this.depTotal = res.data.data.totalRecord;
          this.depList = list.map(item => {
            item.createDate = formatDate(item.createDate);
            return item
          })
        } else {
          this.$message.error(res.data.msg || '服务异常!')
        };
        this.showDep = false
      })
      .catch(e => {
        this.showDep = false;
        this.$message.error('服务异常!')
      })
    },
    openEditDepDialog (data) { // 打开修改科室弹出框
      this.department.department = data.department;
      this.department.departmentId = data.departmentId;
      this.departmentDialogTitle = '修改科室';
      this.showDepartmentDialog = true
    },
    handleDelete (data, type) { // 删除确认
      this.$confirm(`确定将${type === 1 ? '科室' : '职称'}: ${type === 1 ? data.department : data.doctorTitle}删除吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(res => {
        if (type === 1) {
          deleteDepartment(data.departmentId)
          .then(res => {
            if (res.data.code === 1) {
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              this.fetchDepartment(1)
            } else {
              this.$message.error(res.data.msg || '服务异常!')
            }
          })
          .catch(e => {
            this.$message.error('服务异常!')
          })
        } else if (type === 2) {
          deleteCareerTitle(data.doctorTitleId)
          .then(res => {
            if (res.data.code === 1) {
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              this.fetchCareerList(1)
            } else {
              this.$message.error(res.data.msg || '服务异常!')
            }
          })
          .catch(e => {
            this.$message.error('服务异常!')
          })
        }
      })
      .catch(e => {
        this.$message({
          type: 'info',
          message: '取消操作!'
        })
      })
    },
    hideDepDialog () { // 隐藏科室弹出框
      this.showDepartmentDialog = false
    },
    fetchAddDep (name) { // 添加科室信息
      this.$refs[name].validate(valid => {
        if (valid) {
          if (this.departmentDialogTitle === '添加科室') {
            addDepartment({
              department: this.department.department
            })
            .then(res => {
              if (res.data.code === 1) {
                this.$message({
                  type: 'success',
                  message: '操作成功!'
                });
                this.showDepartmentDialog = false;
                this.fetchDepartment(1)
              } else {
                this.$message.error(res.data.msg || '服务异常!')
              }
            })
            .catch(e => {
              this.$message.error('服务异常!')
            })
          } else {
            updateDepartment(this.department)
            .then(res => {
              if (res.data.code === 1) {
                this.$message({
                  type: 'success',
                  message: '操作成功'
                });
                this.showDepartmentDialog = false;
                this.fetchDepartment(1)
              } else {
                this.$message.error(res.data.msg || '服务异常!')
              }
            })
            .catch(e => {
              this.$message.error('服务异常!')
            })
          }
        } else {
          return false
        }
      })
    },
    handleDepPagi (page) { // 科室分页事件
      this.fetchDepartment(page)
    },
    openAddDepDialog () { // 打开科室弹出框
      this.department.department = '';
      this.showDepartmentDialog = true
    },
    hideCareerDialog () { // 隐藏职称弹出框
      this.showCareerDialog = false
    },
    fetchAddCareer (name) { // 添加职称
      this.$refs[name].validate(valid => {
        if (valid) {
          this.isCDoing = true;
          if (this.careerDialogTitle === '添加职称') {
            addCareerTitle({
              doctorTitle: this.career.doctorTitle
            })
            .then(res => {
              if (res.data.code === 1) {
                this.$message({
                  type: 'success',
                  message: '操作成功!'
                });
                this.showCareerDialog = false;
                this.fetchCareerList(1)
              } else {
                this.$message.error(res.data.msg || '服务异常!')
              };
              this.isCDoing = false
            })
            .catch(e => {
              this.isCDoing = false;
              this.$message.error('服务异常!')
            })
          } else {
            updateCareerTitle(this.career)
            .then(res => {
              if (res.data.code === 1) {
                this.$message({
                  type: 'success',
                  message: '操作成功!'
                });
                this.showCareerDialog = false;
                this.fetchCareerList(1)
              } else {
                this.$message.error(res.data.msg || '服务异常!')
              };
              this.isCDoing = false
            })
            .catch(e => {
              this.isCDoing = false;
              this.$message.error('服务异常!')
            })
          }
        } else {
          return false
        }
      })
    },
    fetchCareerList (index) { // 分页查询职称
      this.showCareer = true;
      getCareerTitleByPage({
        count: this.pageSize,
        index
      })
      .then(res => {
        if (res.data.code === 1) {
          let list = res.data.data.list || [];
          this.careerTotal = res.data.data.totalRecord;
          this.careerList = list.map(item => {
            item.createDate = formatDate(item.createDate);
            return item
          });
          console.log(this.careerList)
        } else {
          this.$message.error(res.data.msg || '服务异常!')
        };
        this.showCareer = false
      })
      .catch(e => {
        this.$message.error('服务异常!')
      })
    },
    openEditCareerDialog (data) { // 打开职称弹出框
      this.career.doctorTitle = data.doctorTitle;
      this.career.doctorTitleId = data.doctorTitleId;
      this.careerDialogTitle = '修改职称';
      this.showCareerDialog = true
    },
    openAddCareerDialog () { // 打开职称弹出框
      this.career.doctorTitle = '';
      this.careerDialogTitle = '添加职称';
      this.showCareerDialog = true
    },
    handleCareerPagi (page) { // 职称分页
      this.fetchCareerList(page)
    },
    fetchAreaById (id) {
      getAllArea(id)
      .then(res => {
        if (res.data.code === 1) {
          let list = res.data.data || [];
          if (id === 1) {
            this.countries = list
          } else {
            this.cities = list
          }
        } else {
          this.$message.error(res.data.msg || '服务异常!')
        }
      })
      .catch(e => {
        this.$message.error('服务异常!')
      })
    },
    fetchAllArea () {
      getAllAreaNoPage()
      .then(res => {
        if (res.data.code === 1) {
          let list = res.data.data || [];
          this.allAreaList = list
        } else {
          this.$message.error(res.data.msg || '服务异常!')
        }
      })
      .catch(e => {
        console.log(e)
        this.$message.error('服务异常!')
      })
    },
    getAreaName (id) { // 获取市的名字
      return this.allAreaList.filter(item => item.id === id)[0].cname
    },
    fetchGenQRCode (hId, hName, type) { // 生成医院二维码
      genHospitalQRCode({
        hospitalId: hId,
        hospitalName: hName
      })
      .then(res => {
        if (res.data.code === 1) {
          if (!type) {
            this.showHospitalDialog = false;
          };
          this.fetchHospitals(1)
        } else {
          this.$message.error(res.data.msg || '服务异常!')
        };
        this.isDoing = false;
      })
      .catch(e => {
        this.isDoing = false;
        this.$message.error('服务异常!')
      })
    },
    handleGen ({ hospitalId, hospitalName }) { // 点击生成二维码
      this.fetchGenQRCode(hospitalId, hospitalName, 1)
    },
    goHospitalDetail ({ hospitalId, hospitalName }) { // 进入医院详情
      // this.$router.push(`/mental/hospital/${hospitalId}/${hospitalName}`)
       this.$router.push(`/mental/hospital/${hospitalId}/${enterpriseName}`)
    }
  },
  created () {
    this.fetchHospitals(1);
    this.fetchDepartment(1);
    this.fetchCareerList(1);
    this.fetchAreaById(1);
    // this.fetchAllArea()
  }
}
</script>
<style lang="scss">
  .hospital {

  }
</style>
